<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table
      :data="pageInfo.pageList"
      highlight-current-row
      v-loading="listLoading"
      @selection-change="selsChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="60"> </el-table-column>
      <el-table-column prop="username" label="姓名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="180" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="180" sortable>
      </el-table-column>
      <el-table-column prop="dept.name" label="部门" min-width="180" sortable>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="handleDel(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button
            type="success"
            size="small"
            @click="handleRole(scope.$index, scope.row)"
            >添加角色</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button
        type="danger"
        @click="batchRemove"
        :disabled="this.sels.length === 0"
        >批量删除</el-button
      >
      <!-- <el-pagination
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
				:page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        :total="pageInfo.count"
        style="float: right"
      >
      </el-pagination> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="query.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.count"
        style="float: right"
      >
      </el-pagination>
    </el-col>

    <!--新增界面-->
    <el-dialog
      title="新增"
      :visible.sync="addFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addForm"
        label-width="80px"
        :rules="addFormRules"
        ref="addForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="addForm.age"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="addSubmit"
          :loading="addLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="添加角色"
      :visible.sync="setRoleVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="authrole" label-width="80px" ref="addForm">
        <el-checkbox
          :indeterminate="isRoleterminate"
          v-model="checkAllRole"
          @change="handleRoleCheckAllChange"
          >全选</el-checkbox
        >
        <div
          class="checkbox-table"
          v-for="(p, indexkey) in allRole"
          :key="p.id"
        >
          <template>
            <el-checkbox
              class="check1"
              style="font-weight: 600; margin-bottom: 15px"
              v-model="authrole.allRole"
              :label="p.id"
              @change="handleCheckRole(1, indexkey)"
            >
              {{ p.name }}
            </el-checkbox>
          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRole" :loading="addLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value < 0) {
            callback(new Error('年龄必须大于0'))
          } else if (value > 500) {
            callback(new Error('年龄必须小于500'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入邮箱'))
      }
      setTimeout(() => {
        var em =
          /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
        var flag = em.test(value)
        if (!flag) {
          callback(new Error('请输入正确邮箱'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      filters: {
        name: '',
      },
      users: [],
      pageInfo: {
        count: 0,
        pageList: [],
      },
      query: {
        page: 1,
        pageSize: 10,
      },
      listLoading: false,
      sels: [], //列表选中列

      addFormVisible: false, //新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        age: [{ validator: checkAge, trigger: 'blur' }],
        email: [{ validator: checkEmail, trigger: 'blur' }],
      },
      addRoleRules: {},
      //新增界面数据
      addForm: {
        id: '',
        username: '',
        email: '',
        age: '',
        headImage: '',
        dept: {
          id: '',
          name: '',
        },
      },
      // 所有员工-用于选择管理员
      employees: [],
      deptTree: [],

      // 角色
      setRoleVisible: false,
      isRoleterminate: false,
      authrole: {
        id: null,
        allRole: [], //选中的角色
      },
      checkAllRole: false, //全选状态
      allRole: [], // 所有菜单
      allRoleId: [], //所有角色Id
    }
  },
  methods: {
    search() {
      this.query.page = 1
      this.getEmployees()
    },

    // 点击添加角色
    handleRole(index, row) {
      // 获取所有角色
      this.setRoleVisible = true
      this.getAllRole()
      // 获取所有角色id
      this.getAllRoleId()
      this.authrole.id = row.id
      // 获取用户已有角色
      this.getSnById(row.id)
      console.log("全选状态",this.isRoleterminate);
      debugger
    },
    getSnById(id) {
      this.$http.get('/role/getRole/' + id).then((res) => {
        res = res.data
        if (res.success) {
          this.authrole.allRole = res.data
          // 获取已选中的长度
          let checkedCount = this.authrole.allRole.length
          // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
          this.checkAllRole = checkedCount === this.allRoleId.length
          // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
          this.isRoleterminate =
            checkedCount > 0 && checkedCount < this.allRoleId.length
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getAllRoleId() {
      this.$http.get('/role/ids').then((result) => {
        result = result.data
        if (result.success) {
          // result.resultObj 后端返回的所有的权限sn
          this.allRoleId = result.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 全选触发
    handleRoleCheckAllChange(val) {
      console.log('添加', val)
      this.authrole.allRole = val ? this.allRoleId : []
      this.isRoleterminate = false
    },
    getAllRole() {
      this.$http.get('/role').then((res) => {
        res = res.data
        if (res.success) {
          this.allRole = res.data
        }
      })
    },
    handleCheckRole() {
      // 获取已选中的长度
      let checkedCount = this.authrole.allRole.length
      // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
      this.checkAllRole = checkedCount === this.allRoleId.length
      // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
      this.isRoleterminate =
        checkedCount > 0 && checkedCount < this.allRoleId.length
    },
    saveRole() {
      this.$http.post('/role/addRole', this.authrole).then((res) => {
        res = res.data
        if (res.message) {
          this.$message.success('设置成功')
          this.setRoleVisible = false
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知'
    },
    handleSizeChange(val) {
      this.query.pageSize = val
      this.query.page = 1
      this.getEmployees()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getEmployees()
    },
    //获取员工列表
    getEmployees() {
      let para = {
        currentPage: this.query.page,
        pageSize: this.query.pageSize,
        keyword: this.filters.name,
      }
      // this.listLoading = true;
      //NProgress.start();
      this.$http.post('/employee', para).then((res) => {
        console.log('结果', res.data.data)
        this.pageInfo = res.data.data
      })
      // getUserListPage(para).then((res) => {
      // 	this.total = res.data.total;
      // 	this.users = res.data.users;
      // 	this.listLoading = false;
      // 	//NProgress.done();
      // });
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning',
      })
        .then(() => {
          this.listLoading = true
          this.$http.delete('/employee/' + row.id).then((res) => {
            if (res.data.success) {
              this.$message.success('删除成功')
              this.listLoading = false
              this.query.page = 1
              this.getEmployees()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getAllEmp()
      this.addFormVisible = true
      this.addForm = Object.assign({}, row)
      this.addForm = Object.assign({}, row)
      if (!this.addForm.parent) {
        this.addForm.parent = {
          id: '',
          name: '',
        }
      }
      if (!this.addForm.manager) {
        this.addForm.manager = {
          id: '',
          username: '',
        }
      }
    },
    //显示新增界面
    handleAdd: function () {
      this.getAllEmp()
      this.addFormVisible = true
      this.addForm = {
        id: '',
        username: '',
        email: '',
        age: '',
        headImage: '',
        dept: {
          id: '',
          name: '',
        },
      }
    },
    // 查询所有员工
    getAllEmp() {
      this.$http.get('/employee').then((res) => {
        res = res.data
        this.employees = res.data
      })
    },

    //新增
    addSubmit: function (index, row) {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = false
            //NProgress.start();
            let para = Object.assign({}, this.addForm)
            if (para.parent != null && para.parent != '') {
              for (let index = 0; index < para.parent.length; index++) {
                this.addForm.parent = {
                  id: para.parent[index],
                }
              }
            } else {
              this.addForm.parent = {
                id: null,
              }
            }

            console.log('数据', this.addForm)
            this.$http
              .put('/employee', this.addForm)
              .then((res) => {
                this.addLoading = false
                res = res.data
                if (res.success) {
                  this.$message.success('更新成功')
                  this.addFormVisible = false
                  this.search()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(() => {
                this.$message.error('网络错误')
              })
          })
        }
      })
    },
    selsChange: function (sels) {
      this.sels = sels
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map((item) => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning',
      })
        .then(() => {
          this.listLoading = true
          this.$http.patch('/employee', ids).then((res) => {
            if (res.data.success) {
              this.$message.success('批量删除成功')
              this.listLoading = false
              this.query.page = 1
              this.getEmployees()
            } else {
              this.$message.error(res.data.message)
            }
          })
        })
        .catch(() => {
          this.$message.error('网络异常')
        })
    },
  },
  mounted() {
    this.getEmployees()
  },
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
